var fs = require('fs');
var Promise = require('bluebird');
var config = require('../config');
var utils = require('../common/utils');
var fileresourcedao = require('../dao/fileresourcedao');
var path = require('path');
var filedao = require('../dao/filedao');


module.exports = {
    import: function (data, parent) {
        console.log(parent);
        var dirlist = [];
        var parent_path = parent.path; //.replace(/\\/g, '/');
        dirparse(data, parent_path, dirlist);
        //新增的文件夹
        var newdir = [];
        var olddir = [];
        var idx = 0;
        getTasklist(newdir, olddir, idx, dirlist);
    }
};

function getTasklist(newdir, olddir, idx, dirlist) {
    var dir = dirlist[idx];
    if (dir) {
        fs.exists(dir.data.path, (exists) => {
            if (exists) {
                filedao.check(dir.md5path).then(function (data) {
                    if (data.length == 0) { //目录未入库
                        console.log(dir.data.path + '     未入库,父级目录为：' + dir.data.parent);
                        newdir.push(dir);
                    } else {
                        dir.pid = data[0].pid;
                        olddir.push(dir);
                    }
                    if (idx == dirlist.length) {
                        /*  if (newdir.length > 0) {
                             dirimport(newdir, 0, true);
                         }
                         //
                         if (olddir.length > 0) {
                             olddir.forEach(dir => {
                                 fileDisplay(dir);
                             });
                         } */
                    } else {
                        getTasklist(newdir, olddir, ++idx, dirlist);
                    }
                }, function (err) {
                    console.err(err);
                });
            } else {
                console.log(JSON.stringify(dir));
                console.warn('Dictionary is not exist，import task abort');
            }
        });
    } else {
        if (newdir.length > 0) {
            dirimport(newdir, 0, true);
        }
        //
        if (olddir.length > 0) {
            olddir.forEach(dir => {
                fileDisplay(dir);
            });
        }
    }

}

//保存目录信息
function dirimport(dirarray, index, savefile) {
    var dir = dirarray[index];
    var parent_md5path = utils.md5(dir.data.parent);
    filedao.check(parent_md5path).then(function (pdata) {
        //目录入库                        
        var item = {};
        item.resourceid = utils.generalUUID();
        item.resourcename = dir.data.name;
        item.path = dir.data.path;
        item.resourcetype = dir.data.type; // (dir.data.type == 'directory' ? 0 : 1);

        if (pdata.length > 0) { //找到未入库的目录父级ID
            item.pid = pdata[0].resourceid;
        } else {
            //未找到，说明当前目录为一个新的根目录
            item.pid = '-1';
        }

        item.userid = 1;
        if (dir.data.children && dir.data.children.length == 0) {
            item.isleaf = 1;
        } else {
            item.flag = 1;
        }
        item.md5path = utils.md5(dir.data.path);
        item.flag = 0; //标识此目录入库，但目录下的资源未导入
        fileresourcedao.batchInsert([item], item.resourceid).then(function (data) {
            console.log('目录入库完成:' + dir.data.parent);

            if (savefile) {
                console.log('正在扫描：' + dir.data.path);
                dir.pid = item.resourceid;
                fileDisplay(dir);
            }

            if (index < dirarray.length - 1) {
                index++;
                dirimport(dirarray, index, savefile);
            }
        }, function (error) {
            console.error(error);
        });

    }, function (err) {
        console.error(err);
    });
}

/**
 * 文件遍历方法
 * @param filePath 需要遍历的文件路径
 */
function fileDisplay(dir) {
    var filePath = dir.data.path;
    var filelist = [];
    //根据文件路径读取文件，返回文件列表
    fs.readdir(filePath, function (err, files) {
        if (err) {
            console.warn(err)
        } else {
            var idx = 0;
            //遍历读取到的文件列表
            files.forEach(function (filename) {
                //获取当前文件的绝对路径
                var filedir = path.join(filePath, filename);
                //根据文件路径获取文件信息，返回一个fs.Stats对象
                fs.stat(filedir, function (eror, stats) {
                    idx++;
                    if (eror) {
                        console.warn('获取文件stats失败');
                    } else {
                        var isFile = stats.isFile(); //是文件
                        var isDir = stats.isDirectory(); //是文件夹
                        if (isFile) {
                            console.log(filedir);
                            filelist.push(filedir);
                            if (idx == files.length) {
                                console.log(filePath + '  处理完成');
                                dataimport(dir, filelist);
                            }
                        }
                        /* if (isDir) {
                            fileDisplay(filedir); //递归，如果是文件夹，就继续遍历该文件夹下面的文件
                        } */
                    }


                })
            });
        }
    });
}

//通过配置文件解析出来的目录
//var dirlist = [];
/**
 * 解析配置文件目录
 * 
 */
function dirparse(data, parent_path, dirlist) {
    //var parent_path = parent.path.replace(/\\/g, '/');
    var obj = {};
    obj.name = data.name;
    obj.path = parent_path + '/' + data.name; //data.abspath;
    obj.type = 0;
    obj.parent = parent_path || config.share_folder_root; //父目录
    obj.children = data.children;
    dirlist.push({
        'data': obj,
        'md5path': utils.md5(obj.path)
    });


    //console.log(obj.path + '   md5=' + utils.md5(obj.path));

    if (obj.children && obj.children.length > 0) { //子目录存在
        obj.children.forEach(child => {
            child.parent = obj.path;
            dirparse(child, child.parent, dirlist);
        });
    }
}

function dataimport(dir, filelist) {
    try {
        var length = 0;
        //操作对象
        var list = [];
        filelist.forEach(abspath => {
            length++;
            var item = {};
            item.resourcename = path.basename(abspath);
            item.path = abspath;
            item.resourcetype = 1;
            item.pid = dir.pid;
            item.resourceid = utils.generalUUID();
            item.userid = 1;
            item.isleaf = 0;
            item.flag = 1;
            item.md5path = utils.md5(abspath);
            list.push(item);
            if (filelist.length == length) {
                var resourceid = dir.pid;
                fileresourcedao.batchInsert(list, resourceid).then(function (data) {
                    console.log('文件导入完成:' + abspath);
                }, function (error) {
                    console.error(error);
                });
            }
        });
    } catch (error) {
        console.error(error);
    }


}